// file_picker.dart
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;

// Web 需要 dart:html
import 'dart:html' as html;

class FilePickerHelper {


  /// 选择单个文件并返回 Uint8List 内容
  static Future<Uint8List?> pickFile() async {
    if (kIsWeb) {
      return _pickFileWeb();
    } else {
      return _pickFileNative();
    }
  }

  // ✅ Web 实现
  static Future<Uint8List?> _pickFileWeb() async {
    final completer = Completer<Uint8List?>();

    // 创建文件输入元素
    final input = html.FileUploadInputElement()
    ..multiple = true..accept = '*'
      ..attributes['webkitdirectory'] = 'true'; // 可限制为 'image/*', '.txt' 等
    input.click();

    input.onChange.listen((e) async {
      final files = input.files;
      if (files?.isEmpty == true) {
        completer.complete(null);
        return;
      }
      for(var item in files!) {
        print('选择了 ${item.name} ${item.relativePath} ${item.type}');
      }

      final file = files[0];
      final reader = html.FileReader();
      // 添加错误处理
      reader.onError.listen((error) {
        completer.completeError(error);
      });

      reader.onLoad.listen((_) {
        final result = reader.result;
        if (result is Uint8List) {
          completer.complete(result);
        } else {
          completer.completeError(Exception('Failed to read file as Uint8List'));
        }
      });

      reader.readAsArrayBuffer(file);
    });
    input.onError.listen((error) {
      if (!completer.isCompleted) {
        completer.completeError(error);
      }
    });
    // 用户取消选择
   /* html.document.onClick.listen((_) {
      if (!completer.isCompleted) {
        completer.complete(null);
      }
    });*/

    return completer.future;
  }

  // ✅ 原生实现（需要集成 file_selector 或类似插件）
  // 这里仅示意，实际需添加如 `file_selector` 插件
  static Future<Uint8List?> _pickFileNative() async {
    try {
      // 示例：使用 file_selector
      // final result = await OpenFilePicker.open();
      // if (result == null) return null;
      // return await result.readAsBytes();
      throw UnimplementedError("请集成 file_selector 或类似插件");
    } catch (e) {
      print("文件选择失败: $e");
      return null;
    }
  }
}